﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace VisualGTest
{
    class DurationCell : DataGridViewTextBoxCell
    {
        protected override Object GetFormattedValue(
            Object value,
            int rowIndex,
            ref DataGridViewCellStyle cellStyle,
            TypeConverter valueTypeConverter,
            TypeConverter formattedValueTypeConverter,
            DataGridViewDataErrorContexts context)
        {
            TimeSpan duration = (TimeSpan) value;

            if (duration.TotalMilliseconds < 0)
            {
                return null;
            }
            
            if (duration.TotalMilliseconds < 1000)
            {
                return string.Format("{0}ms", duration.TotalMilliseconds);
            }
            else if (duration.TotalSeconds < 60)
            {
                return string.Format("{0}s", FormatSeconds(duration));
            }
            else if (duration.TotalMinutes < 60)
            {
                return string.Format("{0}m {1}s", duration.Minutes, duration.Seconds);
            }
            else if (duration.TotalHours < 24)
            {
                return string.Format("{0}h {1}m", duration.Hours, duration.Minutes);
            }

            return base.GetFormattedValue(value, rowIndex, ref cellStyle,
                valueTypeConverter, formattedValueTypeConverter, context);
        }

        private string FormatSeconds(TimeSpan duration)
        {
            int millis = duration.Milliseconds;
            string format = "{0:##.###}";

            if (millis % 100 == 0)
            {
                format = "{0:##.#}";
            }
            else if (millis % 10 == 0)
            {
                format = "{0:##.##}";
            }

            return string.Format(format, duration.TotalSeconds);
        }
    }
}
